/**
 * 
 */
package hu.gbalage.owlforms.xforms;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serializer.OutputPropertiesFactory;
import org.apache.xml.serializer.Serializer;
import org.apache.xml.serializer.SerializerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * @author Grill Balazs (balage.g@gmail.com)
 *
 */
public class XMLHelper {

	static DocumentBuilder builder;
	
	static{
		DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
		bf.setNamespaceAware(true);
		try {
			builder = bf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	public static Document createEmptyDoc(){
		return builder.newDocument();
	}
	
	public static Document parse(InputStream input) throws SAXException, IOException{
		return builder.parse(input);
	}
	
	public static void serialize(Document doc, OutputStream output) throws IOException{
		Properties properties = OutputPropertiesFactory.getDefaultMethodProperties("xml");
		properties.setProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR,"/n");
		properties.setProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
		//properties.setProperty(OutputPropertiesFactory.0, null)
		Serializer serializer = SerializerFactory.getSerializer(properties);
		
		serializer.setOutputStream(output);
		serializer.asDOMSerializer().serialize(doc);
	}
	
}
